package fashionshop.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import fashionshop.domain.Store;
import fashionshop.util.HibernateUtil;

public class StoreManageDao {
	
	private static final Logger LOGGER = Logger.getLogger(StoreManageDao.class);
	
	@SuppressWarnings("unchecked")
	public List<Store> getAllStore(){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			Query q = session.createQuery("from Store where historical.isDeleted = false");
			return q.list();
		}catch(Exception ex){
			LOGGER.error("Fail to get all Store", ex);
			throw ex;
		}finally{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Store> searchStore(String name){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			String hql = "from Store where historical.isDeleted = false ";
			if(name != null && !name.isEmpty()){
				hql += "and LOWER(name) like :name";
			}
			Query q = session.createQuery(hql);
			if(name != null && !name.isEmpty()){
				q.setString("name", "%" + name.replace(" ", "%").toLowerCase() + "%");
			}
			return q.list();
		}catch(Exception ex){
			LOGGER.error("Fail to search Store", ex);
			throw ex;
		}finally{
			session.close();
		}
	}
	
	public void deleteStore(long id){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			Query q = session.createQuery("update Store set historical.isDeleted = true where id = :id")
					.setLong("id", id);
			session.beginTransaction();
			q.executeUpdate();
			session.getTransaction().commit();
		}catch(Exception ex){
			LOGGER.error("Fail to delete Store", ex);
			session.getTransaction().rollback();
			throw ex;
		}finally{
			session.close();
		}
	}

}
